/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUITracker.java
 *
 * Created on Mar 23, 2011, 3:44:07 PM
 */

package view;

import com.sun.net.httpserver.HttpServer;
import helper.Utilities;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import main.Peer;
import main.Tracker;
import main.TrackerHandler;

/**
 *
 * @author kuroshaki
 */
public class GUITracker extends javax.swing.JFrame {

    /** Creates new form GUITracker */
    public GUITracker() {
        initComponents();
        mainThread.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        sidelist = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        peerList = new javax.swing.JTextField();
        run = new javax.swing.JButton();
        stop = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        Exit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        About = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        sidelist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sidelistMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(sidelist);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(7, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(peerList, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(peerList, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(219, 219, 219))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        run.setText("Run");
        run.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runActionPerformed(evt);
            }
        });

        stop.setText("Stop");
        stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        Exit.setText("Exit");
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });
        jMenu1.add(Exit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Help");

        About.setText("About");
        jMenu2.add(About);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(213, 213, 213)
                        .addComponent(run)
                        .addGap(85, 85, 85)
                        .addComponent(stop))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stop)
                    .addComponent(run))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void runActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runActionPerformed
        if (!isRun) {
            isRun = true;
            tret.setDaemon(isRun);
            tret.start();
        }
    }//GEN-LAST:event_runActionPerformed

    private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopActionPerformed
        isRun = false;

        tret.setDaemon(isRun);
        server.stop(1);
    }//GEN-LAST:event_stopActionPerformed

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_ExitActionPerformed

    private void sidelistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sidelistMouseClicked
        String selected = sidelist.getSelectedValue().toString();

        CopyOnWriteArrayList<Peer> peers = track.getManage().get(selected);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < peers.size(); ++i) {
            sb.append(peers.get(i).getAddress().toString());
            sb.append("\n");
        }

        StringReader reader = new StringReader(sb.toString());

        try {
            peerList.read(reader, null);
        } catch (IOException iEx) {
            
        }
    }//GEN-LAST:event_sidelistMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUITracker().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem About;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField peerList;
    private javax.swing.JButton run;
    private javax.swing.JList sidelist;
    private javax.swing.JButton stop;
    // End of variables declaration//GEN-END:variables
    private Tracker track = new Tracker();
    private boolean isRun = false;
    private HttpServer server;
    private Thread tret = new BasicThread();


    class BasicThread extends Thread {
        @Override
        public void run() {
            //ListModel listModel = sidelist.getModel();
            while(true){
                Iterator it = track.getManage().entrySet().iterator();
                
                ArrayList<String> torrentList = new ArrayList<String>();

                while (it.hasNext()) {
                    Map.Entry data = (Map.Entry)it.next();

                    torrentList.add((String)data.getKey());
                }

                final String[] daftar = new String[torrentList.size()];
                torrentList.toArray(daftar);

                sidelist.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                sidelist.setLayoutOrientation(JList.VERTICAL_WRAP);
                sidelist.setVisibleRowCount(-1);
                sidelist.setModel(new javax.swing.AbstractListModel() {
                    String[] strings = daftar;
                    public int getSize() { return strings.length; }
                    public Object getElementAt(int i) { return strings[i]; }
                });
                try {
                    it = track.getManage().entrySet().iterator();

                    while (it.hasNext()) {
                        Map.Entry data = (Map.Entry)it.next();

                        CopyOnWriteArrayList<Peer> peers = (CopyOnWriteArrayList<Peer>)data.getValue();
                        ArrayList<Peer> deleted = new ArrayList<Peer>();

                        for (Peer peer : peers){
                            if (peer != null && System.currentTimeMillis() - peer.getLastRequest() > Utilities.INTERVAL) {
                                deleted.add(peer);
                            }
                        }

                        for (Peer peer : deleted){
                            peers.remove(peer);
                        }
                    }

                    track.logFile();

                    sleep(Utilities.PEER_REQUEST_INTERVAL);
                } catch (InterruptedException ex) {
                    System.out.println(ex);
                    Logger.getLogger(GUITracker.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }

    private Thread mainThread = new Thread() {

        @Override
        public void run() {
            InetSocketAddress socket = new InetSocketAddress(Utilities.TRACKER_PORT);
            try {
                server = HttpServer.create(socket, 0);
                server.createContext("/", new TrackerHandler(track));
                server.setExecutor(Executors.newCachedThreadPool());
                server.start();
                System.out.println("Listening to port " + Utilities.TRACKER_PORT);
            } catch (IOException iEx) {
                System.out.println("Error " + iEx);
            }
        }
        
    };
}
